﻿using Microsoft.EntityFrameworkCore;
using shenhao.web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace shenhao.web.Repository
{
    public class BaseRepository<T> where T : class, new()
    {
        private DbContext db;

        public BaseRepository()
        {
            db = MyDbContext.CreateInstance();
        }

        public T AddEntity(T t, bool save = true)
        {
            db.Set<T>().Add(t);
            if (save)
                db.SaveChanges();
            return t;
        }
        public bool Remove(T t)
        {
            db.Entry<T>(t).State = EntityState.Deleted;
            db.SaveChanges();
            return true;
        }
        public T Update(T t)
        {
            db.Entry<T>(t).State = EntityState.Modified;
            db.SaveChanges();
            return t;
        }
        public IQueryable<T> Load(Expression<Func<T, bool>> lambda)
        {
            return db.Set<T>().Where(lambda);
        }
        public IQueryable<T> LoadPage<S>(Expression<Func<T, bool>> lambda, Expression<Func<T, S>> order, int pageIndex, bool IsAsc, out int total)
        {
            var result = db.Set<T>().Where(lambda);
            total = result.Count();
            if (IsAsc)
            {
                result = result.OrderBy<T, S>(order).Skip((pageIndex - 1) * 10).Take(10);
            }
            else
            {
                result = result.OrderByDescending<T, S>(order).Skip((pageIndex - 1) * 10).Take(10);
            }
            return result;
        }
        public void SaveChanges()
        {
            db.SaveChanges();
        }
    }
}
